package org.myhomework.servelet;

import org.myhomework.constant.Constants;
import org.myhomework.dao.UserDao;
import org.myhomework.entity.User;
import org.myhomework.utils.JdbcUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Objects;

public class LoginServlet extends HttpServlet {

    private static final String ADMIN_PAGE = "/admin";
    private static final String TEACHER_PAGE = "/teacher";

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (dealWhenHasLogin(req, resp)) {
            return;
        }
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        boolean success = false;
        User user = UserDao.getByUserName(username);
        if (null != user) {
            if (Objects.equals(user.getPassword(), password)) {
                success = true;
            }
        }
        if (success){
            recordLogin(req, user);
            resp.sendRedirect(Constants.ADMIN_TYPE == user.getType() ? ADMIN_PAGE : TEACHER_PAGE);
            return;
        }
        req.setAttribute("msg", "用户名密码不符，请重试");
        req.setAttribute("back", "/");
        req.getRequestDispatcher("/ok.jsp").forward(req, resp);
    }

    private void recordLogin(HttpServletRequest req, User user) {
        HttpSession session = req.getSession();
        session.setAttribute(Constants.USER_NAME_ATTRIBUTE, user.getUsername());
        session.setAttribute(Constants.USER_ID_ATTRIBUTE, user.getId());
        session.setAttribute(Constants.USER_TYPE_ATTRIBUTE, user.getType());
    }

    private boolean dealWhenHasLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Integer type = (Integer) req.getSession().getAttribute(Constants.USER_TYPE_ATTRIBUTE);
        if (null == type) {
            return false;
        }
        resp.sendRedirect(Constants.ADMIN_TYPE == type ? ADMIN_PAGE : TEACHER_PAGE);
        return true;
    }
}
